package model.server;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerTwo extends Thread{

	int port;
	ServerSocket server;
	boolean stop;
	ClientHandler ch;
	private int noc;
	
	public ServerTwo(int port, int noc, ClientHandler ch) {
		this.port=port;
		stop=false;
		this.ch=ch;
		this.noc=noc;
	}
	
	public void run(){
		try{
			server = new ServerSocket(port);
			System.out.println("Server Started");
			server.setSoTimeout(100000);
			
			ExecutorService tp = Executors.newFixedThreadPool(noc);
			
			try{
				while(!stop){
					System.out.println("Waiting for Client");
					final Socket someClient = server.accept();
					System.out.println("Client Connected");
					final ObjectInputStream inFromClient = new ObjectInputStream(someClient.getInputStream());
					final ObjectOutputStream out2client = new ObjectOutputStream(someClient.getOutputStream());
					
					
					tp.execute(new Runnable() {
						
						@Override
						public void run() {
							ch.handleClient(inFromClient, out2client);
						
							try{
								inFromClient.close();
								out2client.close();
								someClient.close();		
							}catch(Exception e){
								
							}
						}
					});
					
				}
			}catch(SocketTimeoutException e){
			
			}
			server.close();
			System.out.println("Server Closed");
		}catch (IOException e){
			e.printStackTrace();
		}
	}

	public void close(){
		stop=true;
	}
	
}

